#include "map_application_service.h"
#include "infrastructure/map/map_service.h"
#include "infrastructure/map/map_extend_loader.h"
#include "infrastructure/services/common_service.h"
#include "kernel/domain/map.h"
#include "kernel/domain/map_extend_types.h"
#include "application/map/area/area.h"
#include "application/map/charge/charge_point.h"
#include "application/map/park/park_point.h"
#include "application/map/lift/hk_lift.h"
#include "application/map/lift/jz_lift.h"
#include <algorithm>
#include <cmath>
#include <utility>

namespace application {

	MapApplicationService::MapApplicationService(std::shared_ptr<infrastructure::MapService> mapService,
		std::shared_ptr<infrastructure::services::CommonService> commonService,
		std::shared_ptr<infrastructure::MapExtendLoader> extendLoader,
		QObject* parent)
		: QObject(parent)
		, mapService_(mapService)
		, m_logger(commonService ? commonService->loggerFactory()->getLogger("MapApplicationService") : nullptr)
		, m_config(commonService ? commonService->configuration() : nullptr)
		, m_extendLoader(std::move(extendLoader))
		, m_currentPosition(0.0, 0.0)
		, m_currentAngle(0.0)
	{
		if (!mapService_) {
			if (m_logger) {
				m_logger->error("地图服务为空");
			}
			else {
				qWarning() << "地图服务为空";
			}
			return;
		}

		if (!commonService) {
			if (m_logger) {
				m_logger->warning("通用服务为空");
			}
			else {
				qWarning() << "通用服务为空";
			}
			return;
		}

		if (!m_extendLoader) {
			m_extendLoader = std::make_shared<infrastructure::MapExtendLoader>(m_logger);
		}
		m_sharedLiftManager = std::make_shared<lift::LiftManager>(m_logger);
		m_sharedCallerManager = std::make_shared<caller::CallerManager>(m_logger);
		if (m_sharedCallerManager) {
			m_sharedCallerManager->initConnection();
		}
		m_sharedAutoDoorManager = std::make_shared<auto_door::AutoDoorManager>(-1, m_logger);

		if (m_logger) {
			m_logger->info("MapApplicationService initialized successfully");
		}

		connectToMapService();
	}

	kernel::Result<void> MapApplicationService::loadMapFromFile(const QString& filePath) {
		if (!mapService_) {
			return kernel::Result<void>::failure(kernel::ErrorCode::ServiceNotInitialized, "MapService not available");
		}

		auto result = mapService_->loadMapFromFile(filePath);
		if (result.isSuccess()) {
			return kernel::Result<void>::success();
		}
		else {
			return kernel::Result<void>::failure(result.getErrorCode(), result.getErrorMessage());
		}
	}

	kernel::Result<void> MapApplicationService::loadDefaultMap() {
		// 直接调用加载所有地图的方法，它会自动加载默认楼"
		return loadAllMapsFromConfig();
	}

	kernel::Result<void> MapApplicationService::loadAllMapsFromConfig() {
		if (!m_config) {
			if (m_logger) {
				m_logger->error("配置服务不可");
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::ServiceNotInitialized, "Configuration service not available");
		}

		// 从配置中读取地图设置
		auto mapSectionOpt = m_config->getSection("map");
		if (!mapSectionOpt.has_value()) {
			if (m_logger) {
				m_logger->error("配置中未找到地图配置");
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::ConfigurationError, "Map configuration section not found");
		}

		auto mapSection = mapSectionOpt.value();

		// 读取项目名称和默认楼"
		m_itemName = mapSection->getString("itemName", "xipin");
		int defaultFloor = mapSection->getInt("defaultFloor", 2);
		m_esmapConfigIdentifier = mapSection->getString("esmapFilePath", QString());
		if (m_esmapConfigIdentifier.isEmpty()) {
			m_esmapConfigIdentifier = m_itemName;
		}
		m_extendConfigLoaded = false;
		m_cachedExtendData = kernel::MapExtendedData();

		if (m_logger) {
			m_logger->info(QString("开始加载[%1] 的所有地图配置，默认楼层: %2").arg(m_itemName).arg(defaultFloor));
		}

		// 清空现有地图数据
		m_floorMaps.clear();
		m_mapNameToFloor.clear();
		m_registeredLiftNums.clear();
		if (m_sharedLiftManager) {
			for (const auto& lift : m_sharedLiftManager->getAllLifts()) {
				if (lift) {
					m_sharedLiftManager->removeLift(lift->getLiftNum());
				}
			}
		}
		if (m_sharedAutoDoorManager) {
			m_sharedAutoDoorManager->stopConnection();
		}
		m_sharedAutoDoorManager = std::make_shared<auto_door::AutoDoorManager>(-1, m_logger);
		m_sharedThirdAreaManager.reset();
		m_thirdAreaServerStarted = false;
		m_registeredThirdAreaIds.clear();
		m_blockAreaIds.clear();
		initializeThirdAreaManager();

		// 获取数组长度
		int mapsCount = mapSection->getInt("maps:length", 0);
		if (mapsCount == 0) {
			if (m_logger) {
				m_logger->error("配置中没有找到任何地图配");
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::ConfigurationError, "No map configurations found");
		}

		if (m_logger) {
			m_logger->info(QString("发现 %1 个地图配").arg(mapsCount));
		}

		// 遍历数组元素，加载所有楼层的地图
		int loadedCount = 0;
		int successCount = 0;
		for (int i = 0; i < mapsCount; ++i) {
			QString mapPrefix = QString("maps:%1").arg(i);

			auto mapItemSectionOpt = mapSection->getSection(mapPrefix);
			if (!mapItemSectionOpt.has_value()) {
				continue;
			}

			auto mapItemSection = mapItemSectionOpt.value();
			QString userName = mapItemSection->getString("userName", "");
			int floor = mapItemSection->getInt("floor", -1);
			QString filePath = mapItemSection->getString("filePath", userName + ".smap");

			if (userName.isEmpty() || floor < 0) {
				if (m_logger) {
					m_logger->warning(QString("跳过无效的地图配 索引=%1").arg(i));
				}
				continue;
			}

			if (m_logger) {
				m_logger->debug(QString("发现地图配置: 楼层=%1, 名称=%2, 路径=%3")
					.arg(floor).arg(userName).arg(filePath));
			}

			// 创建楼层地图信息
			FloorMapInfo mapInfo;
			mapInfo.floor = floor;
			mapInfo.userName = userName;
			mapInfo.filePath = filePath;
			mapInfo.mapData = nullptr;
			mapInfo.isLoaded = false;

			// 存储到哈希表
			m_floorMaps.insert(floor, mapInfo);
			m_mapNameToFloor.insert(userName, floor);
			loadedCount++;

			// 立即加载该楼层的地图
			if (m_logger) {
				m_logger->info(QString("开始加载%1 楼的地图..").arg(floor));
			}

			auto result = loadFloorMap(m_floorMaps[floor]);
			if (result.isSuccess()) {
				successCount++;
				if (m_logger) {
					m_logger->info(QString("成功加载楼层 %1 的地").arg(floor));
				}
				// 发出单个楼层加载完成信号
				emit floorMapLoaded(floor);
			}
			else {
				if (m_logger) {
					m_logger->error(QString("加载楼层 %1 的地图失败 %2")
						.arg(floor).arg(result.getErrorMessage()));
				}
			}
		}

		if (loadedCount == 0) {
			if (m_logger) {
				m_logger->error("配置中没有找到任何有效的地图配置");
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::ConfigurationError, "No valid map configurations found");
		}

		if (m_logger) {
			m_logger->info(QString("发现 %1 个地图配置，成功加载 %2 ").arg(loadedCount).arg(successCount));
		}

		// 设置默认楼层为当前楼"
		if (m_floorMaps.contains(defaultFloor) && m_floorMaps[defaultFloor].isLoaded) {
			m_currentFloor = defaultFloor;
			if (m_logger) {
				m_logger->info(QString("设置当前楼层为默认楼 %1").arg(defaultFloor));
			}
			emit floorChanged(defaultFloor);
			emit mapLoadFinished();
			return kernel::Result<void>::success();
		}
		else {
			// 如果默认楼层加载失败，使用第一个成功加载的楼层
			for (auto it = m_floorMaps.constBegin(); it != m_floorMaps.constEnd(); ++it) {
				if (it.value().isLoaded) {
					m_currentFloor = it.key();
					if (m_logger) {
						m_logger->warning(QString("默认楼层 %1 加载失败，使用楼%2 作为当前楼层")
							.arg(defaultFloor).arg(m_currentFloor));
					}
					emit floorChanged(m_currentFloor);
					emit mapLoadFinished();
					return kernel::Result<void>::success();
				}
			}

			if (m_logger) {
				m_logger->error("所有楼层的地图都加载失");
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::ConfigurationError, "All floor maps failed to load");
		}
	}

	kernel::Result<void> MapApplicationService::loadFloorMap(const FloorMapInfo& mapInfo) {
		if (!mapService_) {
			return kernel::Result<void>::failure(kernel::ErrorCode::ServiceNotInitialized, "MapService not available");
		}

		if (m_logger) {
			m_logger->info(QString("加载楼层 %1 的地 %2").arg(mapInfo.floor).arg(mapInfo.filePath));
		}

		// 使用 MapService 从文件加载地图，返回 Map 对象
		auto result = mapService_->loadMapFromFile(mapInfo.filePath);
		if (result.isSuccess()) {
			auto& storedInfo = m_floorMaps[mapInfo.floor];
			// 将加载的 Map 对象存储"FloorMapInfo "
			storedInfo.mapData = result.getValue();
			storedInfo.isLoaded = true;

			// 初始化子系统
			initializeSubsystems(storedInfo);
			loadExtendedSubsystemData(storedInfo);

			if (m_logger) {
				m_logger->info(QString("成功加载楼层 %1 的地 %2").arg(mapInfo.floor).arg(mapInfo.userName));
			}

			return kernel::Result<void>::success();
		}
		else {
			if (m_logger) {
				m_logger->error(QString("加载地图失败: %1 - %2")
					.arg(mapInfo.filePath).arg(result.getErrorMessage()));
			}
			return kernel::Result<void>::failure(result.getErrorCode(), result.getErrorMessage());
		}
	}

	void MapApplicationService::initializeSubsystems(FloorMapInfo& mapInfo) {
		if (m_logger) {
			m_logger->info(QString("初始化楼%1 的子系统").arg(mapInfo.floor));
		}

		// 创建区域管理"
		mapInfo.areaManager = std::make_shared<area::AreaManager>(mapInfo.floor, m_logger);
		mapInfo.areaManager->initializeAreas();
		populateAreaManager(mapInfo);

		// 创建充电点管理器
		mapInfo.chargeManager = std::make_shared<charge::ChargeManager>(mapInfo.floor, m_logger);
		mapInfo.chargeManager->initializeChargePoints();

		// 创建停车点管理器
		mapInfo.parkManager = std::make_shared<park::ParkManager>(mapInfo.floor, m_logger);
		mapInfo.parkManager->initializeParkPoints();

        // Share one lift manager across all floors to keep lift resources global
        mapInfo.liftManager = m_sharedLiftManager;

		// 创建呼叫器管理器
		mapInfo.callerManager = m_sharedCallerManager;
		// Caller manager is shared globally (server is started during construction)

		// 创建自动门管理器引用
		mapInfo.autoDoorManager = m_sharedAutoDoorManager;

		// Use shared third-party area manager
		mapInfo.thirdAreaManager = m_sharedThirdAreaManager;

		if (m_logger) {
			m_logger->info(QString("楼层 %1 的子系统初始化完").arg(mapInfo.floor));
		}
	}

	std::shared_ptr<area::AreaManager> MapApplicationService::getAreaManager(int floor) const {
		if (m_floorMaps.contains(floor)) {
			return m_floorMaps[floor].areaManager;
		}
		return nullptr;
	}

	std::shared_ptr<charge::ChargeManager> MapApplicationService::getChargeManager(int floor) const {
		if (m_floorMaps.contains(floor)) {
			return m_floorMaps[floor].chargeManager;
		}
		return nullptr;
	}

	std::shared_ptr<park::ParkManager> MapApplicationService::getParkManager(int floor) const {
		if (m_floorMaps.contains(floor)) {
			return m_floorMaps[floor].parkManager;
		}
		return nullptr;
	}

	std::shared_ptr<lift::LiftManager> MapApplicationService::getLiftManager() const {
		return m_sharedLiftManager;
	}

std::shared_ptr<caller::CallerManager> MapApplicationService::getCallerManager(int floor) const {
	Q_UNUSED(floor);
	return m_sharedCallerManager;
}

	std::shared_ptr<auto_door::AutoDoorManager> MapApplicationService::getAutoDoorManager(int floor) const {
		Q_UNUSED(floor);
		return m_sharedAutoDoorManager;
	}

	std::shared_ptr<third_area::ThirdAreaManager> MapApplicationService::getThirdAreaManager(int floor) const {
		Q_UNUSED(floor);
		return m_sharedThirdAreaManager;
	}

	kernel::Result<void> MapApplicationService::switchToFloor(int floor) {
		if (!m_floorMaps.contains(floor)) {
			if (m_logger) {
				m_logger->error(QString("楼层 %1 不存").arg(floor));
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::InvalidParameter,
				QString("Floor %1 not found").arg(floor));
		}

		const FloorMapInfo& mapInfo = m_floorMaps[floor];

		// 检查楼层是否已加载
		if (!mapInfo.isLoaded) {
			if (m_logger) {
				m_logger->error(QString("楼层 %1 的地图未加载").arg(floor));
			}
			return kernel::Result<void>::failure(kernel::ErrorCode::InvalidOperation,
				QString("Floor %1 map not loaded").arg(floor));
		}

		// 切换到该楼层
		m_currentFloor = floor;

		if (m_logger) {
			m_logger->info(QString("切换到楼%1: %2").arg(floor).arg(mapInfo.userName));
		}

		emit floorChanged(floor);
		emit mapLoadFinished();

		return kernel::Result<void>::success();
	}

	std::shared_ptr<infrastructure::MapService> MapApplicationService::getMapByFloor(int floor) const {
		// MapService 是无状态的文件读取服务，不关联特定楼层
		// 如果需要获取特定楼层的数据，应该先调用 switchToFloor
		if (m_floorMaps.contains(floor) && m_floorMaps[floor].isLoaded) {
			return mapService_;
		}
		return nullptr;
	}

	std::shared_ptr<infrastructure::MapService> MapApplicationService::getMapByName(const QString& mapName) const {
		if (m_mapNameToFloor.contains(mapName)) {
			int floor = m_mapNameToFloor[mapName];
			return getMapByFloor(floor);
		}
		return nullptr;
	}

	int MapApplicationService::getCurrentFloor() const {
		return m_currentFloor;
	}

	QVector<int> MapApplicationService::getLoadedFloors() const {
		QVector<int> floors;
		// 返回所有已配置的楼层，不管是否已加"
		for (auto it = m_floorMaps.constBegin(); it != m_floorMaps.constEnd(); ++it) {
			floors.append(it.key());
		}
		// 排序楼层"
		std::sort(floors.begin(), floors.end());
		return floors;
	}

	void MapApplicationService::refreshMapData() {
		// 数据始终是最新的，只需触发UI刷新
		emit mapLoadFinished();
	}

	kernel::MapDisplayDto MapApplicationService::getMapForDisplay() const {
		auto map = getCurrentMap();
		if (!map) {
			return kernel::MapDisplayDto();
		}

		kernel::MapDisplayDto dto;
		dto.mapName = map->getHeader().mapName;
		dto.bounds = QRectF(map->getHeader().minPos.x, map->getHeader().minPos.y,
			map->getHeader().maxPos.x - map->getHeader().minPos.x,
			map->getHeader().maxPos.y - map->getHeader().minPos.y);
		dto.resolution = map->getHeader().resolution;

		// Convert station points
		const auto& stations = map->getStationPoints();
		dto.stations.reserve(stations.size());
		for (const auto& station : stations) {
			kernel::StationDisplayInfo info(
				QPointF(station.position.x, station.position.y),
				station.instanceName,
				station.className,
				station.property.value
			);
			dto.stations.append(info);
		}

		// Convert bezier paths
		const auto& bezierPaths = map->getBezierPaths();
		for (const auto& path : bezierPaths) {
			kernel::PathDisplayInfo pathInfo;
			pathInfo.name = path.instanceName;
			pathInfo.pathType = "bezier";
			pathInfo.color = path.color;

			// 简化的贝塞尔曲线点生成（可以后续优化）
			pathInfo.points.append(QPointF(path.startPoint.position.x, path.startPoint.position.y));
			pathInfo.points.append(QPointF(path.controlPoint1.x, path.controlPoint1.y));
			pathInfo.points.append(QPointF(path.controlPoint2.x, path.controlPoint2.y));
			pathInfo.points.append(QPointF(path.endPoint.position.x, path.endPoint.position.y));

			dto.paths.append(pathInfo);
		}

		// Convert straight paths
		const auto& straightPaths = map->getStraightPaths();
		for (const auto& path : straightPaths) {
			kernel::PathDisplayInfo pathInfo;
			pathInfo.name = path.instanceName;
			pathInfo.pathType = "straight";
			pathInfo.color = Qt::black;
			pathInfo.points.append(QPointF(path.startPoint.position.x, path.startPoint.position.y));
			pathInfo.points.append(QPointF(path.endPoint.position.x, path.endPoint.position.y));
			dto.paths.append(pathInfo);
		}

		// Convert areas
		const auto& areas = map->getAreas();
		dto.areas.reserve(areas.size());
		for (const auto& area : areas) {
			QVector<QPointF> areaPoints;
			for (int i = 0; i < 4; ++i) {
				areaPoints.append(QPointF(area.corners[i].x, area.corners[i].y));
			}
			dto.areas.append(areaPoints);
		}

		// Sync legacy fields
		dto.syncLegacyFields();

		return dto;
	}

	PathfindingGraphPtr MapApplicationService::getPathfindingGraph(int floor) const {
		auto graph = std::make_shared<PathfindingGraph>();
		auto map = getMapForFloor(floor);

		if (!map) {
			return graph;
		}

		// Add all station points as nodes
		const auto& stations = map->getStationPoints();
		for (const auto& station : stations) {
			const bool avoidWait =
				station.instanceName.startsWith(QStringLiteral("AP"), Qt::CaseInsensitive);
			const QString blockAreaId = getBlockAreaForStation(floor, station.instanceName);
			GraphNode node(station.instanceName,
				station.position.x,
				station.position.y,
				station.direction,
				avoidWait,
				blockAreaId);
			graph->addNode(node);
		}

		// Add edges based on bezier paths
		const auto& bezierPaths = map->getBezierPaths();
		for (const auto& path : bezierPaths) {
			GraphEdge edge(path.startPoint.instanceName,
				path.endPoint.instanceName,
				path.length,
				"bezier");
			graph->addEdge(edge);
		}

		// Add edges based on straight paths
		const auto& straightPaths = map->getStraightPaths();
		for (const auto& path : straightPaths) {
			double dx = path.endPoint.position.x - path.startPoint.position.x;
			double dy = path.endPoint.position.y - path.startPoint.position.y;
			double length = std::sqrt(dx * dx + dy * dy);

			GraphEdge edge(path.startPoint.instanceName,
				path.endPoint.instanceName,
				length,
				"straight");
			graph->addEdge(edge);
		}

		// Mark lift inter_point as avoid-wait nodes to add high penalty for waiting there
		QString mapName = map->getHeader().mapName;
		QString userMapName;
		if (m_floorMaps.contains(floor)) {
			userMapName = m_floorMaps[floor].userName;
		}
		auto floorMatches = [&](const kernel::LiftFloorConfig& floorCfg) -> bool {
			if (floorCfg.floor == floor) {
				return true;
			}
			if (!floorCfg.mapName.isEmpty()) {
				if (!mapName.isEmpty() && floorCfg.mapName == mapName) {
					return true;
				}
				if (!userMapName.isEmpty() && floorCfg.mapName == userMapName) {
					return true;
				}
			}
			return false;
		};
		for (const auto& liftCfg : m_cachedExtendData.lifts) {
			for (const auto& floorCfg : liftCfg.floorInfo) {
				if (!floorCfg.interPoint.isEmpty() && floorMatches(floorCfg)) {
					graph->markAvoidWait(floorCfg.interPoint);
				}
			}
		}

		return graph;
	}

	bool MapApplicationService::isMapLoaded() const {
		return m_currentFloor >= 0 && m_floorMaps.contains(m_currentFloor) && m_floorMaps[m_currentFloor].isLoaded;
	}

	QString MapApplicationService::getCurrentMapName() const {
		auto map = getCurrentMap();
		return map ? map->getHeader().mapName : QString();
	}

	kernel::Position MapApplicationService::getMapBounds() const {
		auto map = getCurrentMap();
		if (!map) {
			return kernel::Position();
		}

		const auto& header = map->getHeader();
		return kernel::Position(header.maxPos.x - header.minPos.x,
			header.maxPos.y - header.minPos.y);
	}

	double MapApplicationService::getMapResolution() const {
		auto map = getCurrentMap();
		return map ? map->getHeader().resolution : 1.0;
	}

	QString MapApplicationService::getStationName(int stationNumber) const {
		auto map = getCurrentMap();
		return map ? map->getStationName(stationNumber) : QString();
	}

	QVector<QString> MapApplicationService::getAllStationNames(int floor) const {
		QVector<QString> names;
		auto map = getMapForFloor(floor);

		if (!map) {
			return names;
		}

		const auto& stations = map->getStationPoints();
		names.reserve(stations.size());
		for (const auto& station : stations) {
			names.append(station.instanceName);
		}
		return names;
	}

	kernel::Position MapApplicationService::getStationPosition(const QString& stationName, int floor) const {
		auto map = getMapForFloor(floor);
		if (!map) {
			return kernel::Position();
		}

		const auto* station = map->findStationPoint(stationName);
		if (station) {
			return station->position;
		}
		return kernel::Position();
	}

	QString MapApplicationService::getAreaIdForStation(int floor, const QString& stationName) const {
		auto area = findAreaForStation(floor, stationName);
		return area ? area->getAreaId() : QString();
	}

	QString MapApplicationService::getBlockAreaForStation(int floor, const QString& stationName) const
	{
		auto area = findAreaForStation(floor, stationName);
		if (!area) {
			return QString();
		}
		auto it = m_blockAreaIds.constFind(floor);
		if (it == m_blockAreaIds.constEnd()) {
			return QString();
		}
		return it->contains(area->getAreaId()) ? area->getAreaId() : QString();
	}

	bool MapApplicationService::isBlockArea(int floor, const QString& areaId) const
	{
		if (areaId.isEmpty()) {
			return false;
		}
		auto it = m_blockAreaIds.constFind(floor);
		if (it == m_blockAreaIds.constEnd()) {
			return false;
		}
		return it->contains(areaId);
	}


	QString MapApplicationService::getMapNameForFloor(int floor) const {
		if (m_floorMaps.contains(floor)) {
			const auto& info = m_floorMaps[floor];
			if (!info.userName.isEmpty()) return info.userName;
		}
		// fallback: current map when floor matches
		if (m_currentFloor == floor) {
			return getCurrentMapName();
		}
		return QString();
	}

	void MapApplicationService::updateCurrentPosition(double x, double y, double angle) {
		m_currentPosition.x = x;
		m_currentPosition.y = y;
		m_currentAngle = angle;
		emit currentPositionChanged();
	}

	kernel::Position MapApplicationService::getCurrentPosition() const {
		return m_currentPosition;
	}

	double MapApplicationService::getCurrentAngle() const {
		return m_currentAngle;
	}

	void MapApplicationService::onMapServiceLoadFinished() {
		if (m_logger) {
			m_logger->info("地图加载完成");
		}
		emit mapLoadFinished();
	}

	void MapApplicationService::onMapServiceLoadFailed(const QString& error) {
		if (m_logger) {
			m_logger->error(QString("地图加载失败: %1").arg(error));
		}
		emit mapLoadFailed(error);
	}

	void MapApplicationService::connectToMapService() {
		if (!mapService_) {
			if (m_logger) {
				m_logger->warning("无法连接地图服务：服务为");
			}
			return;
		}

		// Forward signals from infrastructure layer to presentation layer
		connect(mapService_.get(), &infrastructure::MapService::mapLoadFinished,
			this, &MapApplicationService::onMapServiceLoadFinished);
		connect(mapService_.get(), &infrastructure::MapService::mapLoadFailed,
			this, &MapApplicationService::onMapServiceLoadFailed);

		if (m_logger) {
			m_logger->info("已连接到地图服务");
		}
	}

	void MapApplicationService::initializeThirdAreaManager() {
		m_sharedThirdAreaManager = std::make_shared<third_area::ThirdAreaManager>(m_logger);
		if (!m_sharedThirdAreaManager) {
			return;
		}
		m_sharedThirdAreaManager->setLiftManager(m_sharedLiftManager);
		const quint16 thirdAreaPort = 9001;
		m_thirdAreaServerStarted = m_sharedThirdAreaManager->initConnection(thirdAreaPort);
		if (m_thirdAreaServerStarted) {
			if (m_logger) {
				m_logger->info(QString("全局第三方区域HTTP服务器已启动: 端口=%1").arg(thirdAreaPort));
			}
		} else if (m_logger) {
			m_logger->error(QString("第三方区域HTTP服务器启动失败: 端口=%1").arg(thirdAreaPort));
		}
	}

	// 辅助方法：获取当前楼层的 Map 对象
	std::shared_ptr<kernel::Map> MapApplicationService::getCurrentMap() const {
		return getMapForFloor(m_currentFloor);
	}

	std::shared_ptr<kernel::Map> MapApplicationService::getMapForFloor(int floor) const {
		if (floor < 0 || !m_floorMaps.contains(floor)) {
			return nullptr;
		}

		const FloorMapInfo& mapInfo = m_floorMaps[floor];
		if (!mapInfo.isLoaded || !mapInfo.mapData) {
			return nullptr;
		}

		return mapInfo.mapData;
	}

	int MapApplicationService::getFloorForMapName(const QString& mapName) const {
		if (m_mapNameToFloor.contains(mapName)) {
			return m_mapNameToFloor.value(mapName);
		}
		// fallback: search in floor maps by userName
		for (auto it = m_floorMaps.constBegin(); it != m_floorMaps.constEnd(); ++it) {
			if (it->userName == mapName) return it->floor;
		}
		return -1;
	}

	bool MapApplicationService::ensureExtendConfigLoaded() {
		if (m_extendConfigLoaded) {
			return true;
		}

		if (!m_extendLoader) {
			if (m_logger) {
				m_logger->warning("扩展地图加载器未初始化，跳过esmap加载");
			}
			return false;
		}

		QString identifier = m_esmapConfigIdentifier;
		if (identifier.isEmpty()) {
			identifier = m_itemName;
		}

		auto extendResult = m_extendLoader->loadExtendedData(identifier);
		if (!extendResult.isSuccess()) {
			if (m_logger) {
				m_logger->warning(QString("加载扩展地图失败: %1").arg(extendResult.getErrorMessage()));
			}
			return false;
		}

		m_cachedExtendData = extendResult.getValue();
		m_extendConfigLoaded = true;

		if (m_logger) {
			m_logger->info(QString("扩展地图加载完成: %1，扩展站点=%2")
				.arg(identifier)
				.arg(m_cachedExtendData.stationExtensions.size()));
		}
		return true;
	}

	void MapApplicationService::populateAreaManager(FloorMapInfo& mapInfo) {
		if (!mapInfo.areaManager || !mapInfo.mapData) {
			return;
		}

		auto registerArea = [&](const kernel::Area& sourceArea) -> bool {
			if (sourceArea.instanceName.isEmpty()) {
				return false;
			}
			if (mapInfo.areaManager->hasArea(sourceArea.instanceName)) {
				return false;
			}

			auto runtimeArea = std::make_shared<area::Area>(sourceArea.instanceName);
			double minX = sourceArea.corners[0].x;
			double maxX = minX;
			double minY = sourceArea.corners[0].y;
			double maxY = minY;
			for (int i = 1; i < 4; ++i) {
				minX = std::min(minX, sourceArea.corners[i].x);
				maxX = std::max(maxX, sourceArea.corners[i].x);
				minY = std::min(minY, sourceArea.corners[i].y);
				maxY = std::max(maxY, sourceArea.corners[i].y);
			}

			runtimeArea->setBounds(kernel::Position(minX, minY), kernel::Position(maxX, maxY));
			mapInfo.areaManager->addArea(runtimeArea);
			return true;
		};

		int injectedAreas = 0;
		const auto& advancedAreas = mapInfo.mapData->getAreas();
		for (const auto& area : advancedAreas) {
			if (registerArea(area)) {
				++injectedAreas;
			}
		}

		const auto& blockAreas = mapInfo.mapData->getBlockAreas();
		for (const auto& area : blockAreas) {
			if (registerArea(area)) {
				++injectedAreas;
				m_blockAreaIds[mapInfo.floor].insert(area.instanceName);
			}
		}

		if (m_logger && injectedAreas > 0) {
			m_logger->info(QString("楼层 %1 注入了 %2 个区域定义")
				.arg(mapInfo.floor)
				.arg(injectedAreas));
		}
	}

	void MapApplicationService::loadExtendedSubsystemData(FloorMapInfo& mapInfo) {
		if (!mapInfo.mapData) {
			return;
		}

		if (!ensureExtendConfigLoaded()) {
			return;
		}

		const QString mapName = !mapInfo.userName.isEmpty()
			? mapInfo.userName
			: mapInfo.mapData->getHeader().mapName;

		// 1. 注入站点扩展数据
		int updatedStations = 0;
		for (const auto& extension : m_cachedExtendData.stationExtensions) {
			if (extension.mapName == mapName) {
				auto* station = mapInfo.mapData->findStationPoint(extension.stationName);
				if (station) {
					station->stationType = extension.stationType;
					++updatedStations;
				}
			}
		}

		if (m_logger && updatedStations > 0) {
			m_logger->debug(QString("地图 %1 应用了 %2 个扩展站点信息").arg(mapName).arg(updatedStations));
		}

		// 2. 注入电梯数据
		injectLiftData(mapInfo, mapName);

		// 3. 注入呼叫器数据
		injectCallerData(mapInfo);

		// 4. 注入第三方区域数据
		injectThirdAreaData(mapInfo);

		// 5. 注入充电站数据
		injectChargeStationData(mapInfo, mapName);

		// 6. 注入停车站数据
		injectParkStationData(mapInfo, mapName);

		// 7. 注入自动门数据
		injectAutoDoorData(mapInfo, mapName);
	}

	void MapApplicationService::injectLiftData(FloorMapInfo& mapInfo, const QString& mapName) {
		if (!mapInfo.liftManager) {
			return;
		}

		int injectedLifts = 0;
		int updatedFloors = 0;
		for (const auto& liftConfig : m_cachedExtendData.lifts) {
			std::shared_ptr<lift::BaseLift> liftObj;
			const bool alreadyRegistered = m_registeredLiftNums.contains(liftConfig.liftNum);

			if (!alreadyRegistered) {
				// 创建电梯对象（根据 liftType 选择实现类）
				if (liftConfig.liftType.compare(u"HK", Qt::CaseInsensitive) == 0) {
					liftObj = std::make_shared<lift::HKLift>(
						liftConfig.liftNum,
						liftConfig.liftIp,
						liftConfig.liftPort,
						m_logger
					);
				} else if (liftConfig.liftType.compare(u"JZ", Qt::CaseInsensitive) == 0) {
					liftObj = std::make_shared<lift::JzLift>(
						liftConfig.liftNum,
						liftConfig.baseUrl,
						liftConfig.liftCode,
						m_logger
					);
				} else {
					if (m_logger) {
						m_logger->warning(QString("未知的电梯类型: %1，电梯编号: %2")
							.arg(liftConfig.liftType)
							.arg(liftConfig.liftNum));
					}
					continue;
				}

				// 设置 AGV 控制标志
				liftObj->setAgvControlled(liftConfig.agvControl);

				// 添加楼层信息
				for (const auto& floorConfig : liftConfig.floorInfo) {
					lift::FloorInfo floorInfo;
					floorInfo.floor = floorConfig.floor;
					floorInfo.askPoint = floorConfig.askPoint;
					floorInfo.waitPoint = floorConfig.waitPoint;
					floorInfo.interPoint = floorConfig.interPoint;

					if (!floorInfo.askPoint.isEmpty()) {
						if (auto area = findAreaForStation(floorConfig.floor, floorInfo.askPoint)) {
							floorInfo.askAreaId = area->getAreaId();
						}
					}
					if (!floorInfo.waitPoint.isEmpty()) {
						if (auto area = findAreaForStation(floorConfig.floor, floorInfo.waitPoint)) {
							floorInfo.waitAreaId = area->getAreaId();
						}
					}

					liftObj->addFloorInfo(floorInfo);
				}

				if (!liftObj->initialize()) {
					if (m_logger) {
						m_logger->error(QString("电梯 %1 初始化失败，跳过注入")
							.arg(liftConfig.liftNum));
					}
					continue;
				}

				// 注入到 LiftManager
				mapInfo.liftManager->addLift(liftObj);
				m_registeredLiftNums.insert(liftConfig.liftNum);
				++injectedLifts;
			} else {
				liftObj = mapInfo.liftManager->getLift(liftConfig.liftNum);
				if (!liftObj) {
					continue;
				}
			}

			updatedFloors += updateLiftFloorAreasForMap(liftConfig, mapInfo, liftObj);
		}

		if (m_logger && injectedLifts > 0) {
			m_logger->info(QString("全局电梯管理器注入了 %1 个电梯，首次加载来源地图=%2")
				.arg(injectedLifts)
				.arg(mapName));
		}

		if (m_logger && updatedFloors > 0) {
			m_logger->debug(QString("楼层 %1 更新了 %2 条电梯区域关联").arg(mapInfo.floor).arg(updatedFloors));
		}
	}

	void MapApplicationService::injectCallerData(FloorMapInfo& mapInfo) {
		if (!mapInfo.callerManager) {
			return;
		}

		int injectedCallers = 0;
		for (const auto& callerConfig : m_cachedExtendData.callers) {
			// 检查是否已经注入过这个呼叫器（避免重复注入）
			if (m_registeredCallerNums.contains(callerConfig.callerNum)) {
				continue;
			}

			// 创建呼叫器映射
			mapInfo.callerManager->createTaskConnection(
				callerConfig.callerNum,
				callerConfig.taskName
			);

			m_registeredCallerNums.insert(callerConfig.callerNum);
			++injectedCallers;
		}

		if (m_logger && injectedCallers > 0) {
			m_logger->info(QString("注入了 %1 个呼叫器映射").arg(injectedCallers));
		}
	}

	void MapApplicationService::injectThirdAreaData(FloorMapInfo& mapInfo) {
		if (!mapInfo.thirdAreaManager) {
			return;
		}

		auto areaManager = mapInfo.areaManager;
		int injectedAreas = 0;
		for (const auto& areaConfig : m_cachedExtendData.thirdAreas) {
			if (areaConfig.areaId.isEmpty()) {
				continue;
			}
			const bool alreadyRegistered = m_registeredThirdAreaIds.contains(areaConfig.areaId);

			if (areaConfig.isLiftResource) {
				bool matchesFloor = (areaConfig.floor == 0) || (areaConfig.floor == mapInfo.floor);
				if (!matchesFloor) {
					continue;
				}
				int targetFloor = areaConfig.floor == 0 ? mapInfo.floor : areaConfig.floor;
				if (!alreadyRegistered) {
					mapInfo.thirdAreaManager->addArea(areaConfig.areaId, targetFloor, areaConfig.liftNum);
					m_registeredThirdAreaIds.insert(areaConfig.areaId);
					++injectedAreas;
				}

				if (auto* thirdArea = mapInfo.thirdAreaManager->getArea(areaConfig.areaId)) {
					if (areaManager) {
						thirdArea->linkAreaManager(areaManager.get());
					}
					mapInfo.thirdAreaManager->connectArea(areaConfig.areaId, thirdArea);
				}
				continue;
			}

			if (areaConfig.floor != mapInfo.floor) {
				continue;
			}

			if (!alreadyRegistered) {
				mapInfo.thirdAreaManager->addArea(areaConfig.areaId, areaConfig.floor);
				m_registeredThirdAreaIds.insert(areaConfig.areaId);
				++injectedAreas;
			}

			if (auto* thirdArea = mapInfo.thirdAreaManager->getArea(areaConfig.areaId)) {
				if (areaManager) {
					thirdArea->linkAreaManager(areaManager.get());
				}
				mapInfo.thirdAreaManager->connectArea(areaConfig.areaId, thirdArea);
			}
		}

		if (m_logger && injectedAreas > 0) {
			m_logger->info(QString("¥�� %1 ע���� %2 ������������")
				.arg(mapInfo.floor)
				.arg(injectedAreas));
		}
}

void MapApplicationService::injectChargeStationData(FloorMapInfo& mapInfo, const QString& mapName) {
	if (!mapInfo.chargeManager || !mapInfo.mapData) {
		return;
	}

	int injectedStations = 0;
	for (const auto& chargeConfig : m_cachedExtendData.chargeStations) {
		if (chargeConfig.floor != mapInfo.floor) {
			continue;
		}

		if (chargeConfig.stationPoint.isEmpty()) {
			if (m_logger) {
				m_logger->warning(QString("忽略充电点配置，缺少 station_point (楼层: %1)").arg(mapInfo.floor));
			}
			continue;
		}

		const QString chargePointId = chargeConfig.pointId.isEmpty()
			? chargeConfig.stationPoint
			: chargeConfig.pointId;

		if (chargePointId.isEmpty()) {
			if (m_logger) {
				m_logger->warning(QString("忽略充电点配置，缺少唯一标识 (station_point: %1)").arg(chargeConfig.stationPoint));
			}
			continue;
		}

		if (mapInfo.chargeManager->hasChargePoint(chargePointId)) {
			if (m_logger) {
				m_logger->debug(QString("充电点 %1 已存在，跳过重复注入").arg(chargePointId));
			}
			continue;
		}

		auto* station = mapInfo.mapData->findStationPoint(chargeConfig.stationPoint);
		if (!station) {
			if (m_logger) {
				m_logger->warning(QString("找不到充电站点 %1 (地图: %2)")
					.arg(chargeConfig.stationPoint)
					.arg(mapName));
			}
			continue;
		}

		auto chargePoint = std::make_shared<charge::ChargePoint>(
			chargePointId,
			mapInfo.floor,
			station->position,
			m_logger
		);

		chargePoint->setStationPoint(chargeConfig.stationPoint);
		if (!chargeConfig.actionPoint.isEmpty()) {
			chargePoint->setActionPoint(chargeConfig.actionPoint);
		}
		if (!chargeConfig.supportedAgvTypes.isEmpty()) {
			chargePoint->setSupportedAgvTypes(chargeConfig.supportedAgvTypes);
		}

		// 设置区域（优先使用配置的区域，其次自动匹配站点所在区域）
		std::shared_ptr<area::Area> resolvedArea;
		if (!chargeConfig.areaId.isEmpty() && mapInfo.areaManager) {
			resolvedArea = mapInfo.areaManager->getArea(chargeConfig.areaId);
			if (!resolvedArea && m_logger) {
				m_logger->warning(QString("充电点 %1 指定的区域 %2 不存在")
					.arg(chargePointId)
					.arg(chargeConfig.areaId));
			}
		}

		if (!resolvedArea && mapInfo.areaManager) {
			resolvedArea = mapInfo.areaManager->findAreaContainingPoint(station->position);
			if (!resolvedArea && m_logger) {
				m_logger->warning(QString("充电点 %1 未找到覆盖站点 %2 的区域").arg(chargePointId).arg(chargeConfig.stationPoint));
			}
		}

		chargePoint->setArea(resolvedArea);

		// 设置允许的车辆
		if (!chargeConfig.assignedAgvNumbers.isEmpty()) {
			station->allowedAgvNumbers = chargeConfig.assignedAgvNumbers;
			chargePoint->setAllowedVehicles(chargeConfig.assignedAgvNumbers);
		} else {
			station->allowedAgvNumbers.clear();
			chargePoint->setAllowedVehicles(QList<int>{});
		}

		chargePoint->setBlockedVehicles(chargeConfig.blockedAgvNumbers);

		station->stationType = kernel::StationType::Charge;

		mapInfo.chargeManager->addChargePoint(chargePoint);
		++injectedStations;
	}

	if (m_logger && injectedStations > 0) {
		m_logger->info(QString("地图 %1 注入了 %2 个充电点")
			.arg(mapName)
			.arg(injectedStations));
	}
}

void MapApplicationService::injectParkStationData(FloorMapInfo& mapInfo, const QString& mapName) {
	if (!mapInfo.parkManager || !mapInfo.mapData) {
		return;
	}

	int injectedParks = 0;
	for (const auto& parkConfig : m_cachedExtendData.parkStations) {
		if (parkConfig.floor != mapInfo.floor) {
			continue;
		}

		if (parkConfig.stationPoint.isEmpty()) {
			if (m_logger) {
				m_logger->warning(QString("忽略停车点配置，缺少 station_point (楼层: %1)").arg(mapInfo.floor));
			}
			continue;
		}

		const QString parkPointId = parkConfig.pointId.isEmpty()
			? parkConfig.stationPoint
			: parkConfig.pointId;

		if (parkPointId.isEmpty()) {
			if (m_logger) {
				m_logger->warning(QString("忽略停车点配置，缺少唯一标识 (station_point: %1)").arg(parkConfig.stationPoint));
			}
			continue;
		}

		if (mapInfo.parkManager->hasParkPoint(parkPointId)) {
			if (m_logger) {
				m_logger->debug(QString("停车点 %1 已存在，跳过重复注入").arg(parkPointId));
			}
			continue;
		}

		auto* station = mapInfo.mapData->findStationPoint(parkConfig.stationPoint);
		if (!station) {
			if (m_logger) {
				m_logger->warning(QString("找不到停车站点 %1 (地图: %2)")
					.arg(parkConfig.stationPoint)
					.arg(mapName));
			}
			continue;
		}

		auto parkPoint = std::make_shared<park::ParkPoint>(
			parkPointId,
			mapInfo.floor,
			station->position,
			m_logger
		);
		parkPoint->setStationName(parkConfig.stationPoint);

		std::shared_ptr<area::Area> resolvedParkArea;
		if (!parkConfig.areaId.isEmpty() && mapInfo.areaManager) {
			resolvedParkArea = mapInfo.areaManager->getArea(parkConfig.areaId);
			if (!resolvedParkArea && m_logger) {
				m_logger->warning(QString("停车点 %1 指定的区域 %2 不存在")
					.arg(parkPointId)
					.arg(parkConfig.areaId));
			}
		}

		if (!resolvedParkArea && mapInfo.areaManager) {
			resolvedParkArea = mapInfo.areaManager->findAreaContainingPoint(station->position);
			if (!resolvedParkArea && m_logger) {
				m_logger->warning(QString("停车点 %1 未找到覆盖站点 %2 的区域")
					.arg(parkPointId)
					.arg(parkConfig.stationPoint));
			}
		}

		parkPoint->setArea(resolvedParkArea);

		station->stationType = kernel::StationType::Park;

		mapInfo.parkManager->addParkPoint(parkPoint);
		++injectedParks;
	}

	if (m_logger && injectedParks > 0) {
		m_logger->info(QString("地图 %1 注入了 %2 个停车点")
			.arg(mapName)
			.arg(injectedParks));
	}
}

void MapApplicationService::injectAutoDoorData(FloorMapInfo& mapInfo, const QString& mapName) {
		if (!mapInfo.autoDoorManager) {
			return;
		}

		int injectedDoors = 0;
		for (const auto& doorConfig : m_cachedExtendData.autoDoors) {
			if (doorConfig.floor != mapInfo.floor) {
				continue;
			}
			// 添加自动门到共享管理器
			const bool alreadyExists = mapInfo.autoDoorManager->getDoor(doorConfig.doorId) != nullptr;
			mapInfo.autoDoorManager->addDoor(
				doorConfig.doorId,
				doorConfig.deviceId,
				doorConfig.point1,
				doorConfig.point2,
				doorConfig.openMask,
				doorConfig.closeMask,
				mapInfo.floor
			);
			if (!alreadyExists && mapInfo.autoDoorManager->getDoor(doorConfig.doorId)) {
				++injectedDoors;
			}
		}

		if (m_logger && injectedDoors > 0) {
			m_logger->info(QString("注入了 %1 个自动门，来源地图=%2")
				.arg(injectedDoors)
				.arg(mapName));
		}

		if (mapInfo.autoDoorManager && !mapInfo.autoDoorManager->isServerRunning()) {
			const quint16 port = mapInfo.autoDoorManager->serverPort();
			if (mapInfo.autoDoorManager->initConnection(port) && m_logger) {
				m_logger->info(QString("自动门TCP服务器已启动，端口=%1")
					.arg(mapInfo.autoDoorManager->serverPort()));
			}
		}
	}

	std::shared_ptr<area::Area> MapApplicationService::findAreaForStation(const FloorMapInfo& mapInfo, const QString& stationName) const
	{
		if (!mapInfo.areaManager || !mapInfo.mapData || stationName.isEmpty()) {
			return nullptr;
		}

		auto* station = mapInfo.mapData->findStationPoint(stationName);
		if (!station) {
			return nullptr;
		}

		return mapInfo.areaManager->findAreaContainingPoint(station->position);
	}

std::shared_ptr<area::Area> MapApplicationService::findAreaForStation(int floor, const QString& stationName) const
{
	auto it = m_floorMaps.constFind(floor);
	if (it == m_floorMaps.constEnd()) {
		return nullptr;
	}

	return findAreaForStation(it.value(), stationName);
}

	int MapApplicationService::updateLiftFloorAreasForMap(const kernel::LiftConfig& liftConfig,
	                                                      const FloorMapInfo& mapInfo,
	                                                      const std::shared_ptr<lift::BaseLift>& liftObj)
	{
		if (!liftObj || !mapInfo.areaManager || !mapInfo.mapData) {
			return 0;
		}

		int updated = 0;
		for (const auto& floorConfig : liftConfig.floorInfo) {
			if (floorConfig.floor != mapInfo.floor) {
				continue;
			}

			QString askAreaId;
			QString waitAreaId;

			if (!floorConfig.askPoint.isEmpty()) {
				if (auto area = findAreaForStation(mapInfo, floorConfig.askPoint)) {
					askAreaId = area->getAreaId();
				}
			}

			if (!floorConfig.waitPoint.isEmpty()) {
				if (auto area = findAreaForStation(mapInfo, floorConfig.waitPoint)) {
					waitAreaId = area->getAreaId();
				}
			}

			if (askAreaId.isEmpty() && waitAreaId.isEmpty()) {
				continue;
			}

			if (liftObj->updateFloorAreaInfo(floorConfig.floor, askAreaId, waitAreaId)) {
				++updated;
			}
		}

		return updated;
	}
} // namespace application
